import puppeteer from "puppeteer";
import { vbenConfig } from '../../vbenConfig'
import utilTool from "../../util/tool"
import { SwResult } from "../../store/swResult"
import { createEnumJosnFile } from "../service/createEnum"
import { createApiFile } from "../service/createApi"
import { createApiModelFile } from "../service/createApiModel"
import { createListFile } from "../service/createList"
import { createEditFile } from "../service/createEdit"
import { createRouterFile } from "../service/createRouter"
import { IJson, IResAndReqFieldsMap } from "../../interface/type"
import util from '../common/util'

export class IndexAction {
  private page: puppeteer.Page;
  constructor(page: puppeteer.Page) {
    this.page = page;
  }

  // 根据请求链接的目录来划分模块
  public filterPath(paths: IJson): IJson {
    const obj: IJson = {}
    console.log('paths---------------->', JSON.stringify(paths))
    for (const key of Object.keys(paths)) {
      const item = paths[key].post ? paths[key].post : paths[key].get
      // if (key.indexOf(vbenConfig.baseUrl) > -1) {
      if (item.tags.indexOf(vbenConfig.tagName) > -1) {
        const description = item.description ? item.description : item.summary
        // key.substr(key.indexOf(vbenConfig.baseUrl), key.length).replace(vbenConfig.baseUrl, '')
        const pathArr = key.split('/')
        obj[key] = Object.assign({
          realPath: key,
          apiName: pathArr[pathArr.length - 1],
          description
        }, paths[key])
      }
    }
    return obj
  }

  public async handleSwaggerHook(response: any) {
    const rUrl = response.url()
    if (rUrl.indexOf("/swagger-resources") > 0 && rUrl.indexOf("swagger-resources/configuration/ui") < 0) {
      const json: any[] = await response.json();
      console.log('json---------:', json)
      const obj = json.find(it => { return vbenConfig.serverName === it.name })
      console.log('--请求链接---------->', (vbenConfig.href + obj.url))
      const result = await utilTool.requestGet(vbenConfig.href + obj.url)
      // console.log('结果：', result)
      if (result.code && result.code !== 200) {
        console.log(result.message)
        return
      }
      const sw = new SwResult()
      sw.setDefinitions(result.definitions)
      const pathJson = this.filterPath(result.paths)
      console.log('pathJson>>>>>>>>>>>>>>>>>', pathJson)
      sw.setPaths(pathJson)
      sw.setBasePath(result.basePath)
      if (!result?.definitions) {
        console.log('未获得数据')
        return
      }

      const apiPramAndRes: IResAndReqFieldsMap = {}

      // 需要生成代码的链接组合
      for (const key of Object.keys(pathJson)) {
        const singlePath: IJson = pathJson[key]
        if (!result.paths[key]) {
          continue
        }
        const resObj = util.getResult(singlePath.realPath, sw)
        apiPramAndRes[singlePath.apiName] = resObj
        console.log(`${singlePath.apiName}接口的入参、出参`, JSON.stringify(resObj))
      }

      for (const sPage of vbenConfig.pages) {

        // 创建枚举
        await createEnumJosnFile(apiPramAndRes, sPage)

        // 创建接口出入参数申请明文件
        await createApiModelFile(apiPramAndRes, sPage)
        // 创建接口文件
        await createApiFile(sw, apiPramAndRes, sPage)

        // 创建列表文件，创建数据文件
        await createListFile(sPage, apiPramAndRes)
        // 创建编辑文件
        await createEditFile(sPage, apiPramAndRes)
        await createRouterFile(sPage)
      }
    }
  }

  public async startPageListen(): Promise<void> {
    console.log("开始页面监听");
    // const response = await this.page.waitForResponse(`${vbenConfig.href}/swagger-resources`)
    // this.handleSwaggerHook(response)
    this.page.on("response", async (response: any) => {
      await this.handleSwaggerHook(response)
    })
  }
}
